import Axios from "axios";
import qs from "qs";
import Vue from 'vue';
import { Http } from "./HttpClient";
import {
  Toast,
  Notify
} from "vant";
class Uploader {
  async upload (data, sureBack, failBack) {
    if (data["autoShowWait"]) {
      Toast.loading({
        duration: 0, 
        message: "加载中...",
        forbidClick: true
      });
    }
    // -----------------穿透开发临时代码---------------------------------------------

    let uploadUrl = JSON.parse(Vue.prototype.$dealMsg("HS_URL")).url + '/putFireFeedbackFile';
    //取消8512， 改成56699
    // if(uploadUrl && !uploadUrl.includes("8512")){
    //   //全景：全景图片上传使用8512端口，其他56699
    //   uploadUrl=uploadUrl.replace("56699",'8512') 
    // }
    console.log("uploadUrl=" + uploadUrl)
    let imageFileName = data["imgName"]
    console.log("文件名称：" + imageFileName);
       
    let tformData = new FormData();
    var file;
    if (data["base64URL"]) {
      console.log("----------------含有base64图片");
      if (process.env.VUE_APP_SYSTEM_ENVIRONMENT == 'yixin'  ) {
       // 图钉
       file = this.dataURLtoFile(data["base64URL"], imageFileName);
       tformData.append("file", file, imageFileName + '.jpg');
      }else if(process.env.VUE_APP_SYSTEM_ENVIRONMENT == 'dlydt'){
        // I国网
        var blob = this.dataURLtoFile(data["base64URL"], imageFileName);
        file = new File([blob], imageFileName + '.jpg') // 通过blob创建文件，并设置文件名 
        tformData.append("file", file);
      }
    }else if(data.file){
      console.log("----------------含有图片");
      file = data.file
      tformData.append("file", file);
    }


    //----------------------
    // var blob = new Blob([data["base64URL"]], { type: "image/png" });
    // tformData.append("file", blob);
    
    //----------------------

    
    tformData.append("warnId", data.warnId);
    tformData.append("warnType", data.warnType);
    console.log('warnId:' + data.warnId||'')
    console.log('warnType:' + data.warnType|'')
    Axios.post(uploadUrl, tformData,
      { headers: { 'Content-Type': 'multipart/form-data', Authorization: Vue.prototype.$dealMsg("HS_USER_TOKEN") } }
    )
      .then(result => {
        console.log('全景上传图片响应：' + JSON.stringify(result))
        if (result.data.code == 200) {
          let ret = { url: result.data.msg }
          Toast.clear();
          sureBack && sureBack(ret);
        } else if (result.data.code == 401) {
          var HS = Vue.prototype.$dealMsg("HS_URL") || '{}'
          var baseUrl = JSON.parse(HS).url
          Http.instance().getHSToken(baseUrl)
            .then((ret) => {
              this.upload(data, sureBack, failBack)
            })
        } else {
          console.log('全景服务报错：' , result);
          Toast('全景服务异常，请联系全景平台。异常信息：' + result.data.msg);
          let ret = { url: '' }
          sureBack && sureBack(ret);
        }

      })
      .catch(err => {
        console.log('全景服务报错：' + err);
        failBack && failBack('全景服务异常，请联系全景平台。异常信息：' + err);
        // return Promise.reject(err);
      });

  }

  /**
   * 多图上传
   * @param dataList 数据源
   * @param sureBack 成功回调
   */
  multiUpload (dataList, sureBack, autoShowWait, warnId,warnType) {
    var HS = Vue.prototype.$dealMsg("HS_URL") || '{}'
    var baseUrl = JSON.parse(HS).url
    Http.instance().getHSToken(baseUrl)
      .then((ret) => {
        console.log("获取全景信息：" + JSON.stringify(ret));
        if (autoShowWait) {
          Toast.loading({
            duration: 0,
            message: "加载中...",
            forbidClick: true
          });
        }

        /// 每次多图上传队列置空
        this.uploadedList = [];

        if (dataList.length == 0) {
          sureBack && sureBack([]);
          return;
        }

        for (var i = 0; i < dataList.length; i++) {
          /// 闭包图片上传
          var doUPload = (data, i, length, sureBack) => {
            this.upload({
              imgName: data["imgName"] || `${new Date().getTime()}`,
              base64URL: data["base64URL"],
              file: data['file'],
              moduleName: data['moduleName'],
              warnId: warnId,
              warnType:warnType
            },
              ret => {
                if (ret && ret["url"]) {
                  this.uploadedList[i] = ret["url"];

                  /// 上传队列长度不足，不比对
                  if (this.uploadedList.length < length) {
                    return;
                  }

                  /// 上传队列结果判空
                  var success = true;
                  for (let item of this.uploadedList) {
                    if (!item || item.length == 0) {
                      success = false;
                    }
                  }

                  /// 队列上传成功，返回
                  if (success) {
                    Toast.clear();
                    sureBack && sureBack(this.uploadedList);
                  }
                } else {
                  sureBack([])
                }
              },
              ret => {
                /// 上传失败重新上传
                doUPload(data, i, length, sureBack);
              }
            );
          };
          doUPload(dataList[i], i, dataList.length, sureBack);
        }
      });
      

  }
  dataURLtoFile (dataURI, fileName) {
    let binary = atob(dataURI.split(',')[1]);
    let array = [];
    for (let i = 0; i < binary.length; i++) {
      array.push(binary.charCodeAt(i));
    }
    var blob;
    if (process.env.VUE_APP_SYSTEM_ENVIRONMENT == 'yixin'  ) {
      // 图钉
      blob = new Blob([new Uint8Array(array)], { type: 'application/octet-stream' });
     }else if(process.env.VUE_APP_SYSTEM_ENVIRONMENT == 'dlydt'){
       // I国网
      blob = new Blob([new Uint8Array(array)], { type: 'image/jpeg' });
     }
    // let file = new File([blob], fileName + '.jpg') // 通过blob创建文件，并设置文件名 
    return blob
  }
  async dataURLtoBlob (dataurl) {
    const arr = dataurl.split(",");
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }

    return new Blob([u8arr], {
      type: mime
    });
  }

} 

function randomFloat() {
  // 生成 32 位随机值
  const fooArray = new Uint32Array(1);
  // 最大值是 2^32 –1
  const maxUint32 = 0xFFFFFFFF;
  // 用最大可能的值来除
  return crypto?crypto.getRandomValues(fooArray)[0] / maxUint32:0.5;
}  
export {
  Uploader
};
